package cn.edu.abtu.service.impl;

import cn.edu.abtu.entity.SysPermission;
import cn.edu.abtu.entity.SysUser;
import cn.edu.abtu.mapper.SysUserMapper;
import cn.edu.abtu.service.SysPermissionService;
import cn.edu.abtu.mapper.SysPermissionMapper;
import cn.edu.abtu.service.SysUserService;
import cn.edu.abtu.utils.AjaxResult;
import cn.edu.abtu.utils.MenuTree;
import cn.edu.abtu.vo.RolePermissionVo;
import cn.edu.abtu.vo.query.PermissionQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * (SysPermission)表服务实现类
 *
 * @author makejava
 * @since 2022-11-16 11:48:23
 */
@Slf4j
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {

    @Resource
    private SysPermissionMapper sysPermissionMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 根据用户ID查询权限列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysPermission> getPermissionListByUserId(Long userId) {
        return sysPermissionMapper.getPermissionListByUserId(userId);
    }

    // 查询菜单列表
    @Override
    public List<SysPermission> getPermissionList(PermissionQueryVo permissionQueryVo) {
        QueryWrapper<SysPermission> queryWrapper =new QueryWrapper<>();
        queryWrapper.like(Objects.nonNull(permissionQueryVo.getLabel()),"label",permissionQueryVo.getLabel());
        queryWrapper.orderByAsc("order_num");
        List<SysPermission> permissionList = sysPermissionMapper.selectList(queryWrapper);
        List<SysPermission> menuTree = new ArrayList<>();
        if (!permissionList.isEmpty()){
            // 找到集合中最小的parentId的值
            long parentId = permissionList.stream().mapToLong(SysPermission::getParentId).min().getAsLong();
            menuTree = MenuTree.makeMenuTree(permissionList, parentId);
        }
        return menuTree;
    }

    // 查询上级菜单列表
    @Override
    public List<SysPermission> getParentPermissionList() {
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("type", Arrays.asList(0,1));
        queryWrapper.orderByAsc("order_num");
        List<SysPermission> permissionList = sysPermissionMapper.selectList(queryWrapper);
        SysPermission permission = new SysPermission();
        permission.setId(0L);
        permission.setParentId(-1L);
        permission.setLabel("顶级菜单");
        permissionList.add(permission);
        List<SysPermission> menuTree = MenuTree.makeMenuTree(permissionList, -1L);
        return menuTree;
    }

    @Override
    public AjaxResult deleteById(Long id) {
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        Long count = sysPermissionMapper.selectCount(queryWrapper);
        if (count>0){
            return AjaxResult.error("该菜单下拥有子菜单,无法删除");
        }
        int result = sysPermissionMapper.deleteById(id);
        if (result>0){
            return AjaxResult.success("菜单删除成功!");
        }
        return AjaxResult.error("菜单删除失败!");
    }

    @Override
    public RolePermissionVo getPermissionTree(Long userId, Long roleId) {
        // 查询出当前登陆了用户的信息
        SysUser sysUser = sysUserMapper.selectById(userId);
        List<SysPermission> list = new ArrayList<>();
        if (Objects.nonNull(sysUser) && sysUser.getIsAdmin() == 1){
            list = sysPermissionMapper.selectList(null);
        }else {
            // 根据用户id查询权限信息
            list = sysPermissionMapper.getPermissionListByUserId(userId);
        }
        // 将登录用户所有的权限封装成菜单树
        List<SysPermission> permissionList = MenuTree.makeMenuTree(list, 0L);

        // 根据角色id查询角色所拥有的菜单
        List<SysPermission> rolePermissions = sysPermissionMapper.getPermissionListByRoleId(roleId);
        List<Long> listIds = new ArrayList<>();
        // 进行数据回显
        Optional.ofNullable(list).orElse(new ArrayList<>())
                .stream()
                .filter(Objects::nonNull)
                .forEach(item -> {
                    Optional.ofNullable(rolePermissions).orElse(new ArrayList<>())
                            .stream()
                            .filter(Objects::nonNull)
                            .forEach(obj -> {
                                if (item.getId().equals(obj.getId())){
                                    // 将权限id保存到集合中
                                    listIds.add(obj.getId());
                                    return;
                                }
                            });
                });
        RolePermissionVo rolePermissionVo = new RolePermissionVo(permissionList,listIds.toArray());
        return rolePermissionVo;
    }
}
